const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const proxy= require('http-proxy-middleware');
const cookieSession = require('cookie-session');
const apiRouter = require('./routes/api');
// const bxxRouter = require('./routes/bxx');


const app = express();

//这个中间件的作用就是让app具有存session的功能，并且向前端发cookie
app.use(cookieSession({
  name: 'token',
  keys: ['myuser']
}))
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
//处理前端静态资源
app.use(express.static(path.join(__dirname, 'public')));
//处理ajax接口地址，进入apiRouter
app.use('/api', apiRouter);


// proxy middleware options代理跨域
var options = {
   target: 'https://apiv2.pinduoduo.com', // target host
   changeOrigin: true, // needed for virtual hosted sites
   ws: true, // proxy websockets
   pathRewrite: {
     '^/bxx/api': '/api', // rewrite path
   },
   router: {
     // when request.headers.host == 'dev.localhost:3000',
     // override target 'http://www.example.org' to 'http://localhost:8000'
     'dev.localhost:3000': 'http://localhost:8000'
   }
 }
 // create the proxy (without context)
var exampleProxy = proxy(options);
 //来自bxx的请求使用这个代理
app.use('/bxx', exampleProxy);


module.exports = app;
